package service

import (
	"github.com/vueadmin/app/admin/internal/dto"
	"github.com/vueadmin/app/admin/internal/model"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/app/admin/internal/vo"
	"github.com/vueadmin/utils/conv"
	"path/filepath"
)

type FileService struct {
	svcCtx *svc.ServiceContext
}

func NewFileService(svcCtx *svc.ServiceContext) *FileService {
	return &FileService{
		svcCtx: svcCtx,
	}
}

// 数据列表
func (p FileService) GetPageList(req *dto.FilePageReq) ([]*vo.FileList, int64, error) {
	var (
		entity model.File
		list   []*vo.FileList
		count  int64
	)
	query := p.svcCtx.Db

	order := "id desc"
	query.Model(&entity).Count(&count)
	if err := query.Model(&entity).Limit(req.Limit).Offset((req.Page - 1) * req.Limit).Order(order).Find(&list).Error; err != nil {
		return nil, 0, err
	}
	return list, count, nil
}

// 添加
func (p FileService) Add(req *dto.FileAddReq) (uint, error) {
	entity := model.File{}
	entity.Filepath = req.Filepath
	entity.Hash = conv.StringToSlice(filepath.Base(req.Filepath), ".")[0]
	entity.CreateTime = conv.NowUnix()
	entity.Disk = req.Disk

	if err := p.svcCtx.Db.Create(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

// 删除
func (p FileService) Delete(req *dto.FileDeleteReq) error {
	query := p.svcCtx.Db.Where("filepath IN ?", req.Filepath)
	if err := query.Delete(&model.File{}).Error; err != nil {
		return err
	}
	return nil
}
